package com.ganee.agora.view

import android.os.Bundle
import android.view.*
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.ganee.agora.R
import com.ganee.agora.adapter.BookmarkAdapter
import com.ganee.agora.adapter.SectionFilterAdapter
import com.ganee.agora.adapter.YourListAdapter
import com.ganee.agora.model.FilterItemEntity
import com.ganee.agora.model.InsertActivityEntity
import com.ganee.agora.model.MySection
import com.ganee.agora.model.SearchFilterRequestBody
import com.ganee.agora.viewmodel.SearchFilterViewModel
import com.ganee.agora.widget.recyclerview.MyRecyclerView
import com.ganee.baselib.arouter.Constance
import com.ganee.baselib.httprequest.utils.StringUtils
import com.ganee.baselib.mvvmlibrary.base.BaseActivity
import com.google.gson.Gson
import kotlinx.android.synthetic.main.activity_search_filter.*
import kotlinx.android.synthetic.main.toolbar_with_icon.*
import okhttp3.MediaType
import okhttp3.RequestBody
import java.util.ArrayList

@Route(path = Constance.ACTIVITY_URL_SEARCH_FILTER)
class SearchFilterActivity : BaseActivity<SearchFilterViewModel>(),View.OnClickListener {

    private var categoryList: MutableList<MySection> = ArrayList()
    private var timeList: MutableList<MySection> = ArrayList()
    private var priceList: MutableList<MySection> = ArrayList()
    private var mCategoryAdapter:SectionFilterAdapter? = null
    private var mTimeAdapter:SectionFilterAdapter? = null
    private var mPriceAdapter:SectionFilterAdapter? = null
    private var viewHolderHeader: ViewHolderHeader? = null
    private var mAdapter: BookmarkAdapter? = null
    private val mList = mutableListOf<InsertActivityEntity>()
    private var activeKind:String? = null
    private var activeType:String? = null
    private var activePrice:String? = null
    private var activeTime:String? = null
    private var location:String? = null
    private var roundType:String? = null
    @JvmField
    @Autowired(name = "inputStr")
    var inputStr:String? = null


    private val headerView: View
        get() {
            val view = LayoutInflater.from(this).inflate(R.layout.filter_header_view, filterCategoryRecyclerView.parent as ViewGroup, false)
            viewHolderHeader = ViewHolderHeader(view)
            viewHolderHeader!!.timeRecyclerView!!.setHasFixedSize(false)
            viewHolderHeader!!.timeRecyclerView!!.layoutManager = LinearLayoutManager(this@SearchFilterActivity)

            viewHolderHeader!!.priceRecyclerView!!.setHasFixedSize(false)
            viewHolderHeader!!.priceRecyclerView!!.layoutManager = LinearLayoutManager(this@SearchFilterActivity)

            mTimeAdapter = SectionFilterAdapter(R.layout.item_filter_content, R.layout.item_filter_head, timeList)
            mTimeAdapter!!.onItemClickListener = BaseQuickAdapter.OnItemClickListener { adapter, view, position ->
                val mySection = adapter.getItem(position) as MySection
                val entity = mySection.t as FilterItemEntity
                if (!mySection.isHeader) {
                    for(section in timeList){
                        if (!section.isHeader) {
                            val entity = section.t as FilterItemEntity
                            entity.check = false
                            if (mySection.t.title == entity.title) {
                                entity.check = true
                                activeTime = entity.title
                            }
                        }
                    }
                }
                mTimeAdapter!!.notifyDataSetChanged()
            }
            viewHolderHeader!!.timeRecyclerView!!.adapter = mTimeAdapter

            mPriceAdapter = SectionFilterAdapter(R.layout.item_filter_content, R.layout.item_filter_head, priceList)
            mPriceAdapter!!.onItemClickListener = BaseQuickAdapter.OnItemClickListener { adapter, view, position ->
                val mySection = adapter.getItem(position) as MySection
                val entity = mySection.t as FilterItemEntity
                if (!mySection.isHeader) {
                    for(section in priceList){
                        if (!section.isHeader) {
                            val entity = section.t as FilterItemEntity
                            entity.check = false
                            if (mySection.t.title == entity.title) {
                                entity.check = true
                                activePrice = entity.title
                            }
                        }
                    }
                }
                mPriceAdapter!!.notifyDataSetChanged()
            }
            viewHolderHeader!!.priceRecyclerView!!.adapter = mPriceAdapter

            return view
        }
    override fun getViewModel(): SearchFilterViewModel {
        return ViewModelProviders.of(this@SearchFilterActivity).get(SearchFilterViewModel::class.java)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_search_filter)
        initViewAndData()
        initAdapter()
        initViewAndAdapter()
        initRequestData()
    }

    private fun initViewAndAdapter() {

        filterRecyclerView.setHasFixedSize(true)
        filterRecyclerView.layoutManager = LinearLayoutManager(this)

        mAdapter = BookmarkAdapter(mList)
        filterRecyclerView.addOnItemTouchListener(object : OnItemClickListener() {

            override fun onSimpleItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
                val entity= adapter.getItem(position) as InsertActivityEntity
                ARouter.getInstance().build(Constance.ACTIVITY_URL_HOME_DETAIL).withString("activeId",entity.activeId).navigation()
            }

        })
        filterRecyclerView.adapter = mAdapter
    }


    private fun initRequestData() {
        val inputStr = filter_et_search.text.toString()
        val insertBody = SearchFilterRequestBody(inputStr,activeType,activeKind,activePrice,activeTime,location,roundType)
        val body = Gson().toJson(insertBody)
        val requestBody = RequestBody.create(MediaType.parse("application/json"), body)
        viewModel.getSearchList(requestBody)
        viewModel.searchList.observe(this, Observer<List<InsertActivityEntity>> { list ->
            mList.clear()
            mList.addAll(list)
            filter_tv_total.text = mList.size.toString() + " results"
            mAdapter!!.notifyDataSetChanged()
        })
    }

    private fun initAdapter() {
        filterCategoryRecyclerView.setHasFixedSize(false)
        filterCategoryRecyclerView.layoutManager = LinearLayoutManager(this)
        mCategoryAdapter = SectionFilterAdapter(R.layout.item_filter_content, R.layout.item_filter_head, categoryList)
        mCategoryAdapter!!.onItemClickListener = BaseQuickAdapter.OnItemClickListener { adapter, view, position ->
            val mySection = adapter.getItem(position) as MySection
            if (!mySection.isHeader) {
                for(section in categoryList){
                    if (!section.isHeader) {
                        val entity = section.t as FilterItemEntity
                        entity.check = false
                        if (mySection.t.title == entity.title) {
                            entity.check = true
                            activeKind = entity.title
                        }
                    }
                }
            }
            mCategoryAdapter!!.notifyDataSetChanged()
        }
        mCategoryAdapter!!.setHeaderView(headerView)
        filterCategoryRecyclerView.adapter = mCategoryAdapter
    }

    private fun initViewAndData() {
        val drawerToggle = ActionBarDrawerToggle(this, drawer_layout, null, R.string.app_name, R.string.app_name)
        drawer_layout.addDrawerListener(drawerToggle)
        drawerToggle.syncState()
        toolbarCancel.setOnClickListener(this)
        toolbarRight.visibility = View.VISIBLE
        toolbarRight.setOnClickListener(this)
        filter_tv_reset.setOnClickListener(this)
        filter_tv_confirm.setOnClickListener(this)

        categoryList = getCategoryData()
        timeList = getTimeData()
        priceList = getPriceData()

        filter_et_search.setText(inputStr)
        filter_et_search.setOnEditorActionListener(TextView.OnEditorActionListener { v, actionId, event ->
            if (!StringUtils.isEmpty(v.text.toString())) {
                if (actionId == EditorInfo.IME_ACTION_DONE || event != null && event.keyCode == KeyEvent.KEYCODE_ENTER) {
                    inputStr = filter_et_search.text.toString().trim()
                    initRequestData()
                }
            }
            false
        })
    }

    private fun getTimeData(): MutableList<MySection> {
        val list:MutableList<MySection> = mutableListOf<MySection>()
        list.add(MySection(true, "Time"))
        list.add(MySection(FilterItemEntity("Today", false)))
        list.add(MySection(FilterItemEntity("In 3 Days", false)))
        list.add(MySection(FilterItemEntity("In a week", false)))
        list.add(MySection(FilterItemEntity("Does't matter", false)))
        return list
    }

    private fun getPriceData(): MutableList<MySection> {
        val list:MutableList<MySection> = mutableListOf<MySection>()
        list.add(MySection(true, "Price"))
        list.add(MySection(FilterItemEntity("Price low to high", false)))
        list.add(MySection(FilterItemEntity("Price high to low", false)))
        list.add(MySection(FilterItemEntity("free", false)))
        return list
    }

    private fun getCategoryData(): MutableList<MySection> {
        val list:MutableList<MySection> = mutableListOf<MySection>()
        list.add(MySection(true, "Category"))
        list.add(MySection(FilterItemEntity("music", false)))
        list.add(MySection(FilterItemEntity("drama", false)))
        list.add(MySection(FilterItemEntity("dance", false)))
        list.add(MySection(FilterItemEntity("films", false)))
        list.add(MySection(FilterItemEntity("animals", false)))
        list.add(MySection(FilterItemEntity("exercise", false)))
        list.add(MySection(FilterItemEntity("yoga", false)))
        list.add(MySection(FilterItemEntity("meditation", false)))
        list.add(MySection(FilterItemEntity("nature", false)))
        list.add(MySection(FilterItemEntity("food", false)))
        list.add(MySection(FilterItemEntity("cultural events", false)))
        list.add(MySection(FilterItemEntity("peer support", false)))
        list.add(MySection(FilterItemEntity("spirituality", false)))
        list.add(MySection(FilterItemEntity("visual arts", false)))
        list.add(MySection(FilterItemEntity("museums", false)))
        return list
    }

    override fun onClick(v: View?) {
        when(v!!.id){
            R.id.toolbarCancel -> {
                finish()
            }
            R.id.toolbarRight -> {
                drawer_layout.openDrawer(Gravity.RIGHT)
            }
            R.id.filter_tv_reset -> {
                initReset()
            }
            R.id.filter_tv_confirm -> {
                drawer_layout.closeDrawer(Gravity.RIGHT)
                initRequestData()
            }
        }
    }

    //reset
    private fun initReset() {
        activeTime = ""
        activePrice = ""
        activeKind = ""
        for(section in timeList){
            if (!section.isHeader) {
                val entity = section.t as FilterItemEntity
                entity.check = false
            }
        }
        mTimeAdapter!!.notifyDataSetChanged()
        for(section in priceList){
            if (!section.isHeader) {
                val entity = section.t as FilterItemEntity
                entity.check = false
            }
        }
        mPriceAdapter!!.notifyDataSetChanged()
        for(section in categoryList){
            if (!section.isHeader) {
                val entity = section.t as FilterItemEntity
                entity.check = false
            }
        }
        mCategoryAdapter!!.notifyDataSetChanged()
    }

    internal class ViewHolderHeader(view: View) {
        internal var timeRecyclerView: MyRecyclerView? = null
        internal var priceRecyclerView: MyRecyclerView? = null
        init {
            timeRecyclerView = view.findViewById(R.id.timeRecyclerView) as MyRecyclerView
            priceRecyclerView = view.findViewById(R.id.priceRecyclerView) as MyRecyclerView
        }
    }
}
